#!/usr/bin/python

import sys
import subprocess
import re
from subprocess import Popen
import time
from io import Signal

def getY(yvalue):
    
    y_sensitivity = 7000
    y = "--"
    if int(yvalue) > y_sensitivity :
        y="Forward"
    elif int(yvalue) < (y_sensitivity*-1):
        y="Backward"
    return y

def getX(xvalue):
    
    x_sensitivity = 7000
    x = "--"
    if int(xvalue) > x_sensitivity :
        x="Right"
    elif int(xvalue) < (x_sensitivity*-1):
        x="Left"
    return x


def main():
   
    sig = Signal()
    
    p = Popen(["xboxdrv --detach-kernel-driver"],shell=True,stdout=subprocess.PIPE)
    sensitivity_adjust = 7000

    previous_x = ''
    previous_y = ''
    
    sig.power(1)    

    while p:
        try:    
            line = p.stdout.readline()
            line = line.strip()

            # The line looks like the one given below.    
            # X1: -1026 Y1: -6378  X2: -1048 Y2:  1857  du:0 dd:0 dl:0 dr:0  back:0 guide:0 start:0  TL:0 TR:0  A:0 B:0 X:0 Y:0  LB:0 RB:0  LT:  0 RT:  0
            if line:
                error = re.search('Error',line)
                if error:
                    print line
                    sys.exit(1)
                match = re.search('^X1:\s*(.+)\s+Y1:\s*(.+)\s+X2:\s*(.+)\s+Y2:\s*(.+)\s+',line)
                if match:    
                    x1 = match.group(1)
                    y1 = match.group(2)
                    x2 = match.group(3)
                    y2 = match.group(4)

                    x = getX(x2)
                    y = getY(y1) 
                  
                    #Print only if there is a state change 
                    if previous_x != x or previous_y != y:
                        print x+'('+x2+') ,'+y+'('+y1+')'
                        
                        if y == 'Forward':
                            sig.y_movement(1);
                        elif y == 'Backward':
                            sig.y_movement(-1);
                        else:
                            sig.y_movement(0)
                        
                        if x == 'Right':
                            sig.x_movement(1);
                        elif x == 'Left':
                            sig.x_movement(-1);
                        else:
                            sig.x_movement(0)
                    
                    #Assign current state to previous state for next iteration.
                    previous_x = x
                    previous_y = y
                   
            else:
                #No inputs.. Sleep for a millisecond before checking again
                time.sleep(0.001)
        except KeyboardInterrupt:
            sig.power(0)
            sig.stop()
            print '\nPorts switched off.'
            exit(1)

if __name__ == '__main__':
    main()


